#define max(a, b) ((a)>(b))?(a):(b)
#define min(a, b) ((a)<(b))?(a):(b)
#ifndef __NORMALIZAR__
#define __NORMALIZAR__
unsigned char maxx(unsigned char *src, int fila, int col, int ancho);
unsigned char minn(unsigned char *src, int fila, int col, int ancho);
#endif

void normalizar_local_c (
	unsigned char *src,	//Puntero a la imagen de entrada
	unsigned char *dst,	//Puntero a la imagen destino
	int h,			//Altura de la imagen (REAL)
	int w,			//Ancho de la imagen (REAL)
	int row_size		//Tamaño de una fila
) {
	unsigned char *ppio = src;
	int fila;
	int columna;
	//Copio la primer y ultima linea de pixeles.
	for(columna=0; columna < w; columna ++)
	{
		*(dst+columna) = src[columna];//Primera fila
		*(dst+columna+(w*(h-1))) = src[columna+(w*(h-1))];//Ultima fila
	}
	//Copio la primer y ultima columna de pixeles
	for(fila = 0; fila < h; fila++)
	{
		*(dst+(w*fila)) = src[w*fila];//Primer Columna
		*(dst+(w*fila+w)) = src[w*fila+w];//Ultima columna
	}
	//Hago el filtro con la matriz restante.
	for(fila = 0; fila < h; fila++)
	{
		for(columna = 0; columna < w; columna++)
		{
			unsigned char max = maxx(ppio, fila, columna, w);
			unsigned char min = minn(ppio, fila, columna, w);
			*(dst+columna) = (src[columna]/max)+min;
		}
		dst += w;
		src += w;
	}
}

unsigned char maxx(unsigned char *src, int fila, int col, int ancho)
{
	unsigned char *centro = src + fila*ancho + col;
	unsigned char var1 = max((centro-ancho-1)[0], (centro-ancho)[0]);
	unsigned char var2 = max((centro-ancho+1)[0], (centro-1)[0]);
	unsigned char var3 = max((centro)[0], (centro+1)[0]);
	unsigned char var4 = max((centro+ancho-1)[0], (centro+ancho)[0]);
	unsigned char var5 = max((centro+ancho+1)[0], var1);
	unsigned char var6 = max(max(var2, var3), max(var4, var5));
	return var6;
}

unsigned char minn(unsigned char *src, int fila, int col, int ancho)
{
	unsigned char *centro = src + fila*ancho + col;
	unsigned char var1 = min((centro-ancho-1)[0], (centro-ancho)[0]);
	unsigned char var2 = min((centro-ancho+1)[0], (centro-1)[0]);
	unsigned char var3 = min((centro)[0], (centro+1)[0]);
	unsigned char var4 = min((centro+ancho-1)[0], (centro+ancho)[0]);
	unsigned char var5 = min((centro+ancho+1)[0], var1);
	unsigned char var6 = min(min(var2, var3), min(var4, var5));
	return var6;
}
